# coding=utf-8
__author__ = 'rsg'

import tornado.ioloop
import tornado.web
import tornado.escape
from tornado.options import options
from forms.forms import myForm, LoginForm
from database.connecting import Get_DBSession
from database.models import User
from tornado.web import HTTPError
import json


class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        return self.get_secure_cookie(options.currentuser)


class UserInfoHandler(BaseHandler):
    def get(self):
        return self.render("index.html")

    def post(self):
        #获取表单信息
        form = myForm(self.request.arguments)
        #验证表单并使用表单消息渲染模版
        if self.request.arguments is not None and form.validate():
            m_user_id = form.UserId.data
            m_user_name = form.UserName.data

            #将用户表单信息存储到数据库中
            with Get_DBSession() as dbsession:
                new_user = User(id=m_user_id, name=m_user_name)
                dbsession.add(new_user)
                dbsession.commit()

            return self.render("results.html", user_id=m_user_id, user_name=m_user_name)
        else:
            return self.render("errors.html", err_msg="验证失败!")


class GetUserHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        return self.render("search_user.html", users=None, current_user=self.current_user)

    def post(self, *args, **kwargs):
        #从数据库中获取用户信息
        with Get_DBSession() as dbsession:
            m_users = dbsession.query(User).all()

        return self.render("search_user.html", users=m_users)


class LoginHandler(BaseHandler):
    def get(self):
        #判断是否登陆
        if not self.current_user:
            return self.render("userlogin.html")

        name = tornado.escape.xhtml_escape(self.current_user)
        return self.redirect("/UserInfo/SearchUser")


    def post(self):
        #获取用户提交的数据
        form = LoginForm(self.request.arguments)
        #查询数据库
        with Get_DBSession() as dbsession:
            m_userid = dbsession.query(User).filter(User.id == form.UserId.data)

        if m_userid:
            self.set_secure_cookie('user', self.get_argument("UserId"), expires_days=1)
            return self.write("你已经登陆")
        else:
            return self.write("用户ID错误")


class LogoutHandler(BaseHandler):
    def get(self):
        self.clear_cookie(name="user")
        return self.redirect("/UserLogin")


class ShowPhotoHandler(BaseHandler):
    def get(self):
        return self.render("showphoto.html")


# class MyJsonDecoder(json.JSONDecoder):


class ResponseJsonHandler(BaseHandler):
    def get(self):
        data = json.dumps(options.myjsonobj)
        self.write(data)
        self.set_header("Content-Type", "application/json; charset=utf-8")
        return


class GetJsonHandler(BaseHandler):
    def get(self, *args, **kwargs):
        return self.render("json.html")

    def post(self, *args, **kwargs):
        data = tornado.escape.json_decode(self.get_argument('j_string', None))
        #data = self.request.body
        #obj = json.loads(data)

        return self.write(data)


class WriteJStoClient(BaseHandler):
    def get(self, *args, **kwargs):
        js = 'm_func()'

        self.write(js)
        self.set_header("Content-Type", "application/javascript; charset=utf-8")
        self.flush()

        return


def test():
    class aa(BaseHandler):
        def get(self):
            return self.write('this is test.')
    return 1
test()